<?php

namespace app\admin\controller;

use app\common\controller\Backend;

/**
 * 产品载体
 *
 * @icon fa fa-circle-o
 */
class ClothmakingMaterial extends Backend
{

    /**
     * ClothmakingMaterial模型对象
     * @var \app\admin\model\ClothmakingMaterial
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\ClothmakingMaterial;

    }
    /**
     * 下拉选择数据
     */
    public function selectpage()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        // 搜索关键词
        $search = $this->request->request("q");

        // 分页参数
        $page = $this->request->request("pageNumber");
        $pageSize = $this->request->request("pageSize");

        // 查询构造器
        $query = $this->model
            ->field('id,name,remark') // 只返回必要字段
            ->order('id', 'desc');

        // 搜索条件
        if ($search) {
            $query->where('name', 'like', '%' . $search . '%');
        }

        // 分页查询
        $list = $query->paginate($pageSize, false, ['page' => $page])
            ->toArray();

        // 格式化返回数据
        $result = [
            'list' => $list['data'],
            'total' => $list['total']
        ];

        return json($result);
    }
    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->with('products')->where($pk, 'in', $ids)->select();

        $count = 0;

        foreach ($list as $item) {
            if (!empty($item->products)) {
                $this->error('该项已在产品中使用，不能删除！');
                return;
            }
            $count += $item->delete();
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
